<?php
/**
 * 
 * 
 */	
class Module_DraffController extends  Zend_Controller_Action {
	public function init() {
        //Load cau hinh thu muc trong file config.ini
        $app = Zend_Registry::get('App');
        //Lay duong dan thu muc goc (path directory root)
        $this->view->baseUrl = $baseUrl = $this->_request->getBaseUrl() . "/public/";
        $result = array(
                    array($baseUrl.'lib-js/module/Module_Draff.js','js')
					,array($baseUrl.'css/themes/blitzer/jquery-ui-1.8.14.custom.css','css')
					,array($baseUrl.'lib-js/ui/jquery.ui.datepicker-vi.js','js')
                    ,array($baseUrl.'lib-js/tabs.js','js')
                    ,array($baseUrl.'lib-js/system/upload/css/bootstrap.css','css')
                    ,array($baseUrl.'lib-js/system/upload/css/jquery.fileupload.css','css')
                    ,array($baseUrl.'lib-js/system/upload/css/jquery.fileupload-ui.css','css')
                    ,array($baseUrl.'lib-js/system/upload/js/vendor/jquery.ui.widget.js','js')
                    ,array($baseUrl.'lib-js/system/upload/js/tmpl.min.js','js')
                    ,array($baseUrl.'lib-js/system/upload/js/jquery.iframe-transport.js','js')
                    ,array($baseUrl.'lib-js/system/upload/js/jquery.fileupload.js','js')
                    ,array($baseUrl.'lib-js/system/upload/js/jquery.fileupload-process.js','js')
                    ,array($baseUrl.'lib-js/system/upload/js/jquery.fileupload-ui.js','js')
                );
        if ($this->_request->isXmlHttpRequest()){
            Zend_Layout::startMvc(array(
                'layoutPath' => $app->layout,
                'layout' => 'partial'
            ));
            $this->view->arrJsCss = Zend_Json::encode($result);
        }else{
            //Cau hinh cho Zend_layout
            Zend_Layout::startMvc(array(
                'layoutPath' =>$app->layout,
                'layout' => 'index'
            ));
            //Load ca thanh phan cau vao trang layout (index.phtml)
            $response = $this->getResponse();
           
            //Dinh nghia current modul code
            $this->view->currentModulCode = $this->_request->getParam('controller');
            $this->view->currentModulCodeForLeft = $this->_request->getParam('action');
            $this->view->postHeader = Clound_String::registerFile($result);
            // echo  Clound_String::registerFile($result); die;
            //Hien thi file template
            $response->insert('menu', $this->view->renderLayout('menu.phtml', './application/layout/scripts/'));     //Hien thi header 
			$response->insert('submenu', $this->view->renderLayout('submenu.phtml', './application/layout/scripts/')); 
            $response->insert('footer', $this->view->renderLayout('footer.phtml', './application/layout/scripts/'));   //Hien thi f
        }
    }
    public function indexAction() {
		
    }
	/**
	*	Lấy dữ liệu cho màn hình danh sách
	*
	*/
    public function dataAction(){
        $objDocSend = new Module_Models_Docsend();
        $parames = $this->_request->getParams();
		$parames['Status'] = 'DU_THAO';
		$parames['StaffID'] = Zend_Auth::getInstance()->getIdentity()->StaffID;
        $data = $objDocSend->getAllDocDraff($parames);
        echo Zend_Json::encode($data);
        die;
    }
    public function completedAction() {
		
    }
	
    public function regiterdataAction(){
        $objDocSend = new Module_Models_Docsend();
        $parames = $this->_request->getParams();
		$parames['Status'] = 'CHO_DANG_KY';
		$parames['StaffID'] = Zend_Auth::getInstance()->getIdentity()->StaffID;
        $data = $objDocSend->getAllDocDraff($parames);
        echo Zend_Json::encode($data);
        die;
    }
	
    public function smorderAction() {
		
    }
    public function ropdataAction(){
        $objDocSend = new Module_Models_Docsend();
        $parames = $this->_request->getParams();
		$parames['StaffID'] = Zend_Auth::getInstance()->getIdentity()->StaffID;
        $data = $objDocSend->getAllRopDocDraff($parames);
        echo Zend_Json::encode($data);
        die;
    }
    /**
     * @see : Màn hình thêm, sửa văn bản
     *
     */
    public function addAction() {
		//var_dump($_SESSION);
        if (!$this->_request->isXmlHttpRequest()) {
            return $this->_helper->redirector('index');
        }
		$this->view->addHelperPath('Clound/Xml/Helper/', 'Clound_Xml_Helper');
        $SendID = $this->_request->getParam('SendID');
        //Gan gia tri mac dinh cho cac Input
		if($SendID!=''){
			$objDocSend = new Module_Models_Docsend();
			$model = $objDocSend->selectRow($SendID);
			//Thong tin file dinh kem
			$model['RecordID'] = $SendID.'.docsend.DRAFF';
			//Lay thong tin nguoi nhan
			$modelStaff = new Module_Models_DraffStaff();
			$sRole = 'Y_KIEN_DU_THAO';
			$model['HandleStaffList'] = implode(',',$modelStaff->getStaffByRole($SendID,$sRole));			
		}else{
			$model = array();
		}
		$session = new Clound_Session();
		//Lay can bo co quyen du thao vb
		$session->getsetStaffsByPermission('160011');
		//Lay can bo co quyen ky duyet vb
		$session->getsetStaffsByPermission('160013');		
        // File xml mô tả form
        $filexml = 'xml/module/send/formfield_draff.xml';
        $xmlObj = new Clound_Xml($filexml,$model);
        $formObj = $xmlObj->formfieldGenerate();
        $this->view->form=$formObj;
    }
	/*
	*	Lưu văn bản
	*
	*/
    public function saveAction() {
        $model = new Module_Models_Docsend();
        //Lay cac tham so cua form
		$iSendID = (int)$this->_request->getParam('SendID');
        $sDocType = $this->_request->getParam('DocType');
        $sSubject = trim($this->_request->getParam('Subject'));
        $sNature = $this->_request->getParam('Nature');
		$sEmergency = $this->_request->getParam('Emergency');
		$sReplyDoc = (int)$this->_request->getParam('ReplyDoc');
        $sDraffDate = date('Y/m/d H:i:s');
		
		$iDepartmentDraf = Zend_Auth::getInstance()->getIdentity()->UnitID;
		$iStaffDraf = Zend_Auth::getInstance()->getIdentity()->StaffID;
		$sPositionName = Zend_Auth::getInstance()->getIdentity()->Name;
		
		$iApprovedID = (int)$this->_request->getParam('ApprovedID');
		$oCloundPublic = new Clound_Public();
		$staff = $oCloundPublic->getDepFromStaff($iApprovedID);
		$sApprovedName = $staff['Name'];
		//Can bo cho y kien
		$sHandleStaffList = $this->_request->getParam('HandleStaffList');
		$sXmlData = $this->_request->getParam('XmlData');
		$sTemp = '';
		$sReceivedInfo = $this->_request->getParam('OtherReceived');
		$icheckAdd = 1;
		//Mang gia tri
        $data = array(
            "SendID"			=> 	$iSendID,
            "ReceivedID"		=> 	$sReplyDoc,
            "DocType"			=> 	$sDocType,
			"DraffDate"			=>	$sDraffDate,
            "Nature"			=>	$sNature,
			"Emergency"			=>	$sEmergency,
			"Subject"			=>	$sSubject,
			"XmlData"			=>	$sXmlData,
			"Status"			=>	'DU_THAO',
			"Details"			=>	0,
			"Temp"				=>	$sTemp,
			"StaffID"			=>	$iStaffDraf,
			"PositionName"		=>	$sPositionName,
			"DepartmentID"		=>	$iDepartmentDraf,
			"ApprovedID"		=>	$iApprovedID,
			"ApprovedName"		=>	$sApprovedName,
			"ReceivedInfo"		=>	$sReceivedInfo,
			"OwnerCode"			=>	'TPVT',
        );
        $errors = array();
		$sFileIdList = '';
		$sFileNameList = '';
		//var_dump($data);exit;
		if ($iSendID === 0) {
			$model->insert($data);
			$iSendID = $model->getAdapter()->lastInsertId();
		} else {
			$icheckAdd = 0;
			$where="SendID ='$iSendID'";
			$model->update($data,$where);
		}
		if(!isset($errors['Code'])){
			//Can bo cho y kien
			//Xoa he nhung nguoi khong duoc chon
			$modelStaff = new Module_Models_DraffStaff();
			$modelStaff->deleteNotIn($iSendID,$sHandleStaffList);
			//Insert nguoi moi
			if($sHandleStaffList){
				$count = sizeof($sHandleStaffList);
				for ($i = 0; $i < $count; $i++) {
					//Kiem tra co ton tai hay ko
					if($modelStaff->isValid($iSendID,$sHandleStaffList[$i],'Y_KIEN_DU_THAO')){
						$staff = $oCloundPublic->getDepFromStaff($sHandleStaffList[$i]);
						//Mang gia tri
						$data = array(
							"DraffHandleStaffID"			=> 	0,
							"DocID"							=> 	$iSendID,
							"DepartmentID"					=> 	$staff['UnitID'],
							"StaffID"						=> 	$sHandleStaffList[$i],
							"PositionName"					=> 	$staff['Name'],
							"Role"							=> 	'Y_KIEN_DU_THAO',
							"ReceiveDate"					=> 	$sDraffDate,
							"Status"						=> 	'CHO_XU_LY'
						);
						$modelStaff->insert($data);
					}
				}
			}
			//Xu ly file dinh kem
			$fileObj = new Clound_File(null,false);
			$modelFile = new System_Models_File();
			//Lay file dinh kem
			$arrSign = $model->selectRow($iSendID);				
			$sFileIdList = $arrSign['FileID'];
			$sFileNameList = $arrSign['FileName'];
			//Xoa file
			$sDeleteFileList = $this->_request->getParam('deleteFileList');
			//echo $sDeleteFileList;exit;
			if ($sDeleteFileList != '') {
				$arrFileIdList = explode(',', $sFileIdList);
				$arrFileNameList = explode('!#!', $sFileNameList);			
				$arrDeleteFile = explode('!#~$|*', $sDeleteFileList);
				$count = sizeof($arrDeleteFile);
				for ($i = 0; $i < $count; $i++) {
					$arrTemp = explode('.', $arrDeleteFile[$i]);
					$arrFile = $modelFile->getFileView($arrTemp);
					$delete = $modelFile->deleteRows($arrFile['FileID']);
					$fileObj->_deleteFileAttach($arrFile['FileName']);
					$arrFileIdList = array_diff($arrFileIdList, array($arrFile['FileID']));
					$arrFileNameList = array_diff($arrFileNameList, array($arrFile['FileName']));
				}
				$sFileIdList = implode(',',$arrFileIdList);
				$sFileNameList = implode('!#!', $arrFileNameList);				
			}
			//echo $sFileNameList;exit;
			//File dinh kem
			$sAttachfile = $this->_request->getParam('attachfile');
			$arrFileNameList = array();
			if ($sAttachfile != '') {
				$arrFileNameList = $fileObj->_uploadFileAttachList($sAttachfile);
			}
			$count = sizeof($arrFileNameList);
			if($count){
				for ($i = 0; $i < $count; $i++) {
					$sFileId = '';
					//Mang gia tri
					$data = array(
						"FileID"			=> 	0,
						"RecordID"			=> 	$iSendID,
						"RecordType"		=> 	'DRAFF',
						"FileType"			=> 	strtolower(pathinfo($arrFileNameList[$i], PATHINFO_EXTENSION)),
						"FileName"			=> 	$arrFileNameList[$i],
						"TableName"			=> 	'docsend'
					);
					$modelFile->insert($data);
					$sFileId = $modelFile->getAdapter()->lastInsertId();
					if($sFileIdList==''){
						$sFileIdList = $sFileId;
						$sFileNameList = $arrFileNameList[$i];
					}else{
						$sFileIdList .= ','.$sFileId;
						$sFileNameList .= '!#!'.$arrFileNameList[$i];
					}
				}
			}
			$data = array(
						"SendID"		=> 	$iSendID,
						"FileID"		=> 	$sFileIdList,
						"FileName"		=> 	$sFileNameList
					);
			$where="SendID ='$iSendID'";
			$model->update($data,$where);
			//Them tien do
			if($icheckAdd){
				$modelWork = new Module_Models_WorkSend();
				//Mang gia tri
				$data = array(
					"WorkID"			=> 	0,
					"DocID"				=> 	$iSendID,
					"StaffID"			=> 	$iStaffDraf,
					"PositionName"		=> 	$sPositionName,
					"DepartmentID"		=> 	$iDepartmentDraf,
					"WorkType"			=> 	'150001', //150001
					"WorkDate"			=> 	$sDraffDate,
					"Result"			=> 	$sSubject,
					"FileID"			=> 	$sFileIdList,
					"FileName"			=> 	$sFileNameList
				);
				$modelWork->insert($data);				
			}
		}
        echo Zend_Json::encode($errors);
        die;
    }
    /**
     * @see : Màn hình xử lý văn bản
     *
     */
    public function processAction() {
		//var_dump($_SESSION);
        if (!$this->_request->isXmlHttpRequest()) {
            return $this->_helper->redirector('index');
        }
		$this->view->addHelperPath('Clound/Xml/Helper/', 'Clound_Xml_Helper');
        $SendID = $this->_request->getParam('SendID');
        //Gan gia tri mac dinh cho cac Input
		$objDate = new Clound_Datetime();
		$sProcessDate = $objDate->ToDdMMyyyy();		
		$model = array(
			'ProcessDate' 	=> $sProcessDate,
			'SendID'		=> $SendID,
			'ProcessType' 	=> '150002'
		);
		$session = new Clound_Session();
		//Lay can bo co quyen ky duyet vb
		$session->getsetStaffsByPermission('160013');		
        // File xml mô tả form
        $filexml = 'xml/module/send/formfield_process.xml';
        $xmlObj = new Clound_Xml($filexml,$model);
        $formObj = $xmlObj->formfieldGenerate();
        $this->view->form=$formObj;
    }
    public function ropprocessAction() {
		//var_dump($_SESSION);
        if (!$this->_request->isXmlHttpRequest()) {
            return $this->_helper->redirector('index');
        }
        $SendID = $this->_request->getParam('SendID');
        //Lay thong tin co ban
		$objDocSend = new Module_Models_Docsend();
		$model = $objDocSend->selectRow($SendID);
		//var_dump($model);exit;
		$objDate = new Clound_Datetime();
		$objDate->set($model['DraffDate'],'yyyy-MM-dd HH:mm:ss');
		$model['SendDate'] = $objDate->toString('dd/MM/yyyy HH:mm:ss');
		$fileObj = new Clound_File(null,false);
		$model['Subject'] = $fileObj->SumContenAndFile('Subject','SendID','docsend','DRAFF',$model);
		$oCacheFile = new Clound_CacheFile();
		$arrDocType = $oCacheFile->getList('DM04');			
		$oCloundPublic = new Clound_Public();
		$model['DocType'] = $oCloundPublic->getNameByCode($arrDocType, $model['DocType']);		
		$this->view->model = $model;
		$session = new Clound_Session();
		//Lay can bo co quyen ky duyet vb
		$session->getsetStaffsByPermission('160013');		
    }
    public function processdataAction() {
		//Lay thong tin qua trinh xu ly
        $SendID = $this->_request->getParam('SendID');
		$modelObj = new Module_Models_WorkSend();
		$model = $modelObj->getAllProcess($SendID);
        echo Zend_Json::encode($model);
        die;
    }
    /**
     * @see : Màn hình xử lý văn bản
     *
     */
    public function regiterAction() {
		//var_dump($_SESSION);
        if (!$this->_request->isXmlHttpRequest()) {
            return $this->_helper->redirector('index');
        }
		$this->view->addHelperPath('Clound/Xml/Helper/', 'Clound_Xml_Helper');
        $SendID = $this->_request->getParam('SendID');
        //Gan gia tri mac dinh cho cac Input
		$objDate = new Clound_Datetime();
		$sProcessDate = $objDate->ToDdMMyyyy();		
		$model = array(
			'ProcessDate' 	=> $sProcessDate,
			'SendID'		=> $SendID,
			'ProcessType' 	=> '150006'
		);
		$session = new Clound_Session();
		//Lay can bo co quyen ky duyet vb
		$session->getsetStaffsByPermission('160013');		
        // File xml mô tả form
        $filexml = 'xml/module/send/formfield_process.xml';
        $xmlObj = new Clound_Xml($filexml,$model);
        $formObj = $xmlObj->formfieldGenerate();
        $this->view->form=$formObj;
    }	
    /**
     * @see : Màn hình xử lý văn bản
     *
     */
    public function saveprocessAction() {
        $model = new Module_Models_Docsend();
        //Lay cac tham so cua form
		$iSendID = (int)$this->_request->getParam('SendID');
		$objDate = new Clound_Datetime();
		$sProcessDate = $objDate->convertDateTime($this->_request->getParam('ProcessDate'));
		$sResult = trim($this->_request->getParam('Result'));
		$sProcessType = $this->_request->getParam('ProcessType');
		$sProcessType = $sProcessType[0];
		if($sProcessType==='150005'){
			//Update trang thai
			$data = array(
						"SendID"		=> 	$iSendID,
						"Status"		=> 	'TRINH_KY'
					);
			$where="SendID ='$iSendID'";
			$model->update($data,$where);
			//Update lanh dao duyet
			$modelStaff = new Module_Models_DraffStaff();
			//Insert nguoi moi
			$iApprovedID = $this->_request->getParam('ApprovedID');
			if($iApprovedID){
				//Kiem tra co ton tai hay ko
				if($modelStaff->isValid($iSendID,$iApprovedID,'PHE_DUYET')){
					$oCloundPublic = new Clound_Public();
					$staff = $oCloundPublic->getDepFromStaff($iApprovedID);
					//Mang gia tri
					$data = array(
						"DraffHandleStaffID"			=> 	0,
						"DocID"							=> 	$iSendID,
						"DepartmentID"					=> 	$staff['UnitID'],
						"StaffID"						=> 	$iApprovedID,
						"PositionName"					=> 	$staff['Name'],
						"Role"							=> 	'PHE_DUYET',
						"ReceiveDate"					=> 	$sProcessDate,
						"Status"						=> 	'CHO_DUYET'
					);
					$modelStaff->insert($data);
				}
			}
		}elseif($sProcessType==='150006'){
			//Update trang thai
			$data = array(
						"SendID"		=> 	$iSendID,
						"Status"		=> 	'CHO_PHAT_HANH'
					);
			$where="SendID ='$iSendID'";
			$model->update($data,$where);			
		}
		//Update tien do
		$modelWork = new Module_Models_WorkSend();
		//Mang gia tri
		$iDepartmentDraf = Zend_Auth::getInstance()->getIdentity()->UnitID;
		$iStaffDraf = Zend_Auth::getInstance()->getIdentity()->StaffID;
		$sPositionName = Zend_Auth::getInstance()->getIdentity()->Name;		
		$data = array(
			"WorkID"			=> 	0,
			"DocID"				=> 	$iSendID,
			"StaffID"			=> 	$iStaffDraf,
			"PositionName"		=> 	$sPositionName,
			"DepartmentID"		=> 	$iDepartmentDraf,
			"WorkType"			=> 	$sProcessType,//150002
			"WorkDate"			=> 	$sProcessDate,
			"Result"			=> 	$sResult
		);
		$errors = array();
		$errors = $modelWork->insert($data);
		$iWorkID = $modelWork->getAdapter()->lastInsertId();
		//Update file
		$fileObj = new Clound_File(null,false);
		$modelFile = new System_Models_File();
		$sFileIdList = '';
		$sFileNameList = '';
		$sAttachfile = $this->_request->getParam('attachfile');
		$arrFileNameList = array();
		if ($sAttachfile != '') {
			$arrFileNameList = $fileObj->_uploadFileAttachList($sAttachfile);
		}
		$count = sizeof($arrFileNameList);
		if($count){
			for ($i = 0; $i < $count; $i++) {
				$sFileId = '';
				//Mang gia tri
				$data = array(
					"FileID"			=> 	0,
					"RecordID"			=> 	$iWorkID,
					"RecordType"		=> 	'WORK',
					"FileType"			=> 	strtolower(pathinfo($arrFileNameList[$i], PATHINFO_EXTENSION)),
					"FileName"			=> 	$arrFileNameList[$i],
					"TableName"			=> 	'worksend'
				);
				$modelFile->insert($data);
				$sFileId = $modelFile->getAdapter()->lastInsertId();
				if($sFileIdList==''){
					$sFileIdList = $sFileId;
					$sFileNameList = $arrFileNameList[$i];
				}else{
					$sFileIdList .= ','.$sFileId;
					$sFileNameList .= '!#!'.$arrFileNameList[$i];
				}
			}
		}	
		$data = array(
					"WorkID"		=> 	$iWorkID,
					"FileID"		=> 	$sFileIdList,
					"FileName"		=> 	$sFileNameList
				);
		$where="WorkID ='$iWorkID'";
		$modelWork->update($data,$where);
        echo Zend_Json::encode($errors);
        die;
    }
    /**
     * @see : Thuc hien viec xoa Mot hoac Nhieu văn bản đi
     */
    public function deleteAction() {
        $model = new Module_Models_Docsend;
        $sDocSendIDList = $this->_request->getParam('ListIDs');
        echo Zend_Json::encode($model->deleteRows($sDocSendIDList));
        die();
    }
}?>
